package com.shixianjun.leetcode;

public class _21_合并两个有序链表 {

    static public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        /**
         * 第一想法也是双指针
         * */

        if (list1 == null || list2 == null) {
            return list1 == null ? list2 : list1;
        }

        ListNode basic = null, other = null;
        if (list1.val <= list2.val) {
            basic = list1;
            other = list2;
        } else {
            basic = list2;
            other = list1;
        }

        ListNode head = basic;


        while (basic != null && other != null) {

            if (basic.next == null) {
                basic.next = other;
                break;
            }

            if (basic.val <= other.val && other.val <= basic.next.val) {
                ListNode next = basic.next;
                basic.next = other;
                other = other.next;
                basic.next.next = next;
            }

            basic = basic.next;
        }

        return head;
    }

    public static void main(String[] args) {
        int[] num1 = {1, 2, 4};
        int[] num2 = {1, 3, 4};
        ListNode list1 = new ListNode(num1);
        ListNode list2 = new ListNode(num2);

        System.out.print(list1);
        System.out.print(list2);

        ListNode result = mergeTwoLists(list1, list2);
        System.out.print(result);
    }
}
